package cn.peach.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

@Component
public class CheckLoginFilter extends ZuulFilter {

    @Override
    public String filterType() {
        // 前置filter
        return "pre";
    }

    @Override
    public int filterOrder() {
        // 执行顺序  小->大
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 是否执行run方法返回值
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String uri = request.getRequestURI();
        if (uri.endsWith("login") || uri.endsWith("register")) {
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext cC = RequestContext.getCurrentContext();
        HttpServletRequest request = cC.getRequest();
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            HttpServletResponse response = cC.getResponse();
            try {
                response.setContentType("application/json;charest=utf-8");
                response.getWriter().write("请登录");
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 阻止继续往后执行
            cC.setSendZuulResponse(false);
        }
        // token不为空 就放行
        return null;
    }
}
